<template>

    <div class="base-page" v-if="isShow">
        <div class="left">
            <select-org @select="onSelectOrg" />
        </div>
        <div class="right">
            <div class="e-table">
                <div class="top">
                    <div class="left">
                        <div class="left-btn">
                            <el-button size="mini"  @click="buttonAdd()" style="background: #7aa818; color: #fff">新增</el-button>
                            <el-button size="mini"  @click="start()">启用</el-button>
                            <el-button size="mini"  @click="block()">停用</el-button>
                            <el-button type="danger" size="mini" @click="ctDelete">删除</el-button>
                            <el-button size="mini" @click="Lock()">锁定物资</el-button>
                        </div>
                    </div>
                    <div class="search_box">
                        <el-input class="ipt" type="text"
                            placeholder="输入搜索关键字"
                            v-model="searchKey"
                            @select="onSearch"
                            @change="onSearch"
                        ><img src="@/assets/search.png" slot="suffix" @click="onSearch" /></el-input>
                        <div class="adverse">
                            <el-button type="primary" @click="onAdvanceSearch">高级搜索</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="e-table" :style="{width: rightTableWidth}">

                <el-table
                    class="table"
                    :height="rightTableHeight"
                    :data="tableData"
                    border
                    :cell-class-name="cellClsNm"
                    highlight-current-row
                    @current-change="handleCurrentChange"
                    @selection-change="planTableSelect"
                     ref="table"
                v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'table' }"
                >
                    <el-table-column
                    fixed
                    type="index"
                    label="序号"
                    width="80"
                    align="center"
                    ></el-table-column>
                    <el-table-column prop="orgName" label="机构名称" min-width="200" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="state" label="状态" width="100" >
                         <template slot-scope="{ row }">
                             <span>{{['停用','启用'][row.state]}}</span>
                         </template>
                     </el-table-column>
                    <el-table-column prop="isAuthorize" label="分子公司授权" width="150">
                         <template  slot-scope="{ row }">
                              <el-button type="primary" size="mini" @click="Authorize(row)" v-if="row.isAuthorize === 0 || row.isAuthorize == null"
                                >未授权</el-button>
                                 <el-button type="primary" size="mini" @click="Authorize(row)" v-else
                                >已授权</el-button>
                         </template>
                         </el-table-column>

                </el-table>
            </div>
            <Pagination
                :total="paginationInfo.total"
                :pageSize.sync="paginationInfo.pageSize"
                :currentPage.sync="paginationInfo.currentPage"
                @currentChange="getTableData"
                @sizeChange="getTableData"
            />
        </div>

    </div>

     <div class="base-page " v-else>
            <div class="right" >
                <div class="e-form" style="padding: 0 10px 10px;">
                    <el-form ref="form" :model="formData" label-width="150px">
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="机构名称：">
                                    <el-input v-model="formData.orgName"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="状态：">
                                 <el-select v-model="formData.state" placeholder="请选择">
                                    <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                    </el-option>
                                </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="footer">
                    <div class="right-btn">
                        <el-button type="primary" size="mini"
                        @click="onSave"
                        >保存</el-button>
                        <el-button type="default" size="mini"
                            @click="onCancel"
                        >取消</el-button>
                    </div>
                </div>
            </div>
        </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import SelectOrg from '@/pages/materialsmanagement/sendReceiveLock/selectOrgName'
import Pagination from '@/components/pagination/pagination'
// eslint-disable-next-line no-unused-vars
import { getreceivingAndIssuingLock, AddreceivingAndIssuingLock, startBlock, createOrUpdateReceivingLock, createOrUpdateIssuanceLock } from '@/api/materials/sendReceiveLock'
// eslint-disable-next-line no-unused-vars
import { debounce, advanceSearch, showLoading, hideLoading, selectDataClient, openAppClient } from '@/utils/common'
import { mapMutations, mapState } from 'vuex'
export default {
    components: {
        Pagination,
        SelectOrg
    },
    computed: {
        ...mapState(['userInfo']),
        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 300) + 'px'
        },
        // 列表高度
        rightTableHeight () {
            if (this.paginationInfo.total > 0) {
                return this.screenHeight - 170
            } else {
                return this.screenHeight - 118
            }
        },
        // 分配用户、分配岗位列表宽度
        rightTableWidth2 () {
            return (this.screenWidth - 300) + 'px'
        },
        rightTableHeight2 () {
            return this.screenHeight - 210
        }

    },
    data () {
        return {
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            searchKey: '',
            treeData: [],
            currentRow: null,
            paginationInfo: {
                total: 0,
                pageSize: 10,
                currentPage: 1,
            },
            tableData: [],
            allData: [],
            formData: {
                'billId': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'isAuthorize': null,
                'orgId': '',
                'orgName': '',
                'state': ''
            },
            currencyOptions: [],

            isUsing: '',
            options: [{
                value: '0',
                label: '停用'
            }, {
                value: '1',
                label: '启用'
            }],
            tabsName: 'baseInfo',
            tableData2: [],
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            idsTop: [],
            isclick: false, //是否点击
            selection: [],
            isShow: true,

            p1: {}, //收料
            p2: {}//发料
        }
    },
    created () {
        this.getTableData()
    },
    mounted () {
        // 获取屏幕宽高
        this.getScreenInfo()
        window.addEventListener('resize', debounce(this.getScreenInfo))
    },

    methods: {
        ...mapMutations(['setSelectedInfo']),
        //新增按钮
        buttonAdd () {
            if(this.isclick) {
                this.isShow = false
            }else{
                this.clientPop('info', '请先选择组织机构！')
            }

        },
        //启用
        start () {
            if(this.formData.billId === '') {
                this.clientPop('info', '请先选择要启用的数据!')
            }else{
                if(this.formData.state === '1') {
                    this.clientPop('info', '已经启用!')
                }else{
                    this.formData.state = '1'
                    let info = '启用成功'
                    this.startAndBlock(info)
                }
            }
        },
        //停用
        block () {
            if(this.formData.billId === '') {
                this.clientPop('info', '请先选择要停用的数据!')
            }else{
                if(this.formData.state === '0') {
                    this.clientPop('info', '已经停用!')
                }else{
                    this.formData.state = '0'
                    let info = '停用成功'
                    this.startAndBlock(info)
                }
            }
        },
        startAndBlock (info) {
            startBlock(this.formData).then(()=>{
                this.clientPop('suc', info, ()=>{
                    this.getTableData()
                })
            })
        },
        //授权
        Authorize (row) {

            if(row.isAuthorize === 0 || row.isAuthorize == null) {
                this.clientPop('info', `是否授权于:${row.orgName}`, ()=>{
                    this.isAuthorize(row.billId, 1)
                })

            }else if(row.isAuthorize === 1) {
                this.clientPop('info', `是否取消授权于:${row.orgName}`, ()=>{
                    this.isAuthorize(row.billId, 0)
                })
            }

        },
        //授权请求
        isAuthorize (p1, p2) {
            this.$Ajax
                .httpGet({
                    url: '/material/receivingAndIssuingLock/updateAuthorizeState',
                    params: {
                        billId: p1,
                        isAuthorize: p2,
                    },

                }).then(()=>{
                    this.clientPop('suc', '操作成功', this.getTableData)
                })
        },
        //锁定物资
        Lock () {
            if(this.formData.billId === '') {
                this.clientPop('info', '请先选择要锁定的数据!')
            }else{

                let ids = []
                selectDataClient({
                    SelectServiceToken: '/material/categoryLibrary/queryListByParentId',
                    IsSingleMode: true, // 是否单选 true 单选 false 多选
                    SelectedIDs: ids, //
                    InitParamsStr: JSON.stringify({
                        'estimatedMaterialLock': null, //暂估物资锁(0：否;1：是)
                        'isCentralizedPurchasing': null, //集中采购(0：否;1：是)
                        'parentiId': '0', //父级id
                        'topClassNameNeed': [], //需要的物资类别(顶级类别名称)
                        'topClassNameNeedless': []//不需要的物资类别(顶级类别名称)
                    }),
                    Title: '' // 标题
                }).then(val=>{
                    this.setSelectedInfo(val)
                    let obj1 = {
                        materialCategorys: [],
                        orgId: this.formData.orgId,
                    }
                    let obj2 = {
                        materialCategorys: [],
                        orgId: this.formData.orgId,
                    }

                    val[0].forEach(item=>{
                        item.categoryId = item.billId
                        item.categoryName = item.className
                        obj1.materialCategorys.push(item)
                    })
                    val[1].forEach(item=>{
                        item.categoryId = item.billId
                        item.categoryName = item.className
                        obj2.materialCategorys.push(item)
                    })

                    this.saveStoreIssue(obj1)
                    this.saveReceivingIn(obj2)
                })
            }
        },
        //保存，更新或删除收料锁物资类别
        saveStoreIssue (obj) {
            createOrUpdateReceivingLock(obj).then(()=>{ this.clientPop('suc', '锁定收料成功!', this.getTableData)})
        },
        //保存，更新或删除发料锁物资类别
        saveReceivingIn (obj) {
            createOrUpdateIssuanceLock(obj).then(()=>{ this.clientPop('suc', '锁定发料成功!', this.getTableData)})
        },
        //保存
        onSave () {
            console.log('this.formData', this.formData)
            AddreceivingAndIssuingLock(this.formData).then(()=>{
                this.clientPop('suc', '保存成功!', ()=>{
                    this.onCancel(),
                    this.getTableData()
                })
            })

        },
        //删除
        ctDelete () {
            if(this.formData.billId === '') {
                this.clientPop('info', '请先选择要删除的数据!')
            }else{

                this.clientPop(
                    'info',
                    this.oneDeleteErr,
                    this.delData
                )
            }
        },
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/receivingAndIssuingLock/delete',
                    params: {
                        id: this.formData.billId,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.getTableData())
                    }
                })
        },
        //获取选择项
        planTableSelect (selection) {
            this.selection = selection
        },

        handleCurrentChange (val) {
            this.formData = val
        },
        async getTableData () {
            // showLoading()
            try {
                const resData = await getreceivingAndIssuingLock({
                    orgid: this.formData.orgid,
                    states: [],
                    limit: this.paginationInfo.pageSize,
                    page: this.paginationInfo.currentPage
                })
                console.log('resData', resData.list)
                this.tableData = resData.list
                // this.allData = JSON.parse(JSON.stringify(resData.list))
                // this.paginationInfo.total = resData.totalCount
                // this.viewList = true
                // hideLoading()
            } catch (error) {
                hideLoading()
            }
        },
        async queryTableData () {
            const resData = this.allData.filter(item => {
                return item.userName.includes(this.searchKey)
            })
            this.tableData = resData
            this.paginationInfo.total = 0
        },
        //
        onSelectOrg (val) {
            this.isclick = true
            console.log('orgId>>>>>', val)
            this.formData = {
                ...val,
            }
            this.getTableData()
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        onSearch (e) {
            let searchKey = e
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            console.log(searchKey)
            this.queryTableData()
        },
        onAdvanceSearch () {
            advanceSearch().then(res => {
                alert(JSON.stringify(res))
            })
        },
        goList () {
            this.viewList = true
        },

        // // 点击分配角色按钮
        // async onDistRole () {
        //     this.viewList = 'role'
        //     const data = await getRoleByOrg({
        //         orgId: this.currentRow.orgId,
        //         userId: this.currentRow.userId
        //     })
        //     this.tableData2 = data.filter(item => item.userId)
        // },
        // 选择角色
        // onSelectRole () {
        //     const SelectedIDs = this.tableData2.map(item => item.roleId)
        //     selectDataClient({
        //         SelectServiceToken: '/hr/role/getOrgRole', // 客户端对应方法名
        //         IsSingleMode: false, // 是否单选 true 单选 false 多选
        //         SelectedIDs, // 已选中id
        //         InitParamsStr: JSON.stringify({
        //             orgId: this.currentRow.orgId,
        //             userId: ''
        //         }),
        //         Title: '选择角色' // 标题
        //     }).then(val => {
        //         val.forEach(item => {
        //             console.log('item', item)
        //             // item.userId = this.currentRow.userId
        //             // item.userName = this.currentRow.userName
        //         })
        //         // 保存用户选择返回数据到store
        //         // this.setSelectedInfo(val)
        //         // openAppClient('/showSelectedData', '选择结果')
        //         this.tableData2 = val
        //     })
        // },
        // 保存分配角色
        // async onSave () {
        //     showLoading()
        //     try {
        //         await saveOrgRoleApi({
        //             url: {
        //                 orgId: this.currentRow.orgId,
        //                 userId: this.currentRow.userId,
        //             },
        //             params: this.tableData2
        //         })
        //         hideLoading()
        //         this.clientPop('suc', '保存成功', () => {
        //             this.getTableData()
        //         })
        //     } catch (error) {
        //         hideLoading()
        //     }
        //     this.viewList = true
        // },
        onDel (index) {
            this.tableData2.splice(index, 1)
        },
        onCancel () {
            this.isShow = true
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        },
    }
}
</script>

<style lang="scss" scoped>
.el-form{
    padding-top: 25px;
}
</style>
